#!/usr/bin/env python3

from Bio import Entrez, Medline


Entrez.email = "liqiming1914658215@gmail.com"                                      
Entrez.api_key = "c80ce212c7179f0bbfbd88495a91dd356708"

impact_dict = {}

with open("Journa_impact.tsv") as f:
    for line in f:
        tokes = line.rstrip().split("\t")
        impact_dict[tokes[0]] = tokes[1]

print(impact_dict)

map_impact = open("PubMed_Journal_Impact_factor.tsv", "w")

for journal, factor in impact_dict.items():
    handle = Entrez.esearch(db="pubmed", term=f"{journal}[ta]", retmax=10)
    record = Entrez.read(handle)
    idlist = record["IdList"]

    if not idlist:
        continue

    handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="text")
    records = Medline.parse(handle)
    for record in records:
        pubmed_journal = record.get("TA", "")

        if pubmed_journal:
            break
    if not pubmed_journal:
        continue

    print(f"{journal}\t{pubmed_journal}\t{factor}")
    map_impact.write(f"{journal}\t{pubmed_journal}\t{factor}\n")

map_impact.close()
